# -*- coding: utf-8 -*-

from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators import csrf
from blog.models import Data,SubjectiveEvaluationResult,EvaluationResults
from django.views.decorators.csrf import csrf_exempt
from django.db import connection
import json
import datetime
import random
import os,sys

def hello(request):
	return HttpResponse("Hello world ! ")

def index(request):
	return render(request,'index.html')

def home(request):
	return render(request,'Home.html')

def analyze(request):
	return render(request,'analyze.html')

def optanalyze(request):
	return render(request,'optanalyze.html')

@csrf_exempt
def forms(request):
	if request.method == 'POST':
		print '@'*20
		video_id = request.POST['video_id']
		score_one = request.POST['video1_score']
		score_two = request.POST['video2_score']
		with connection.cursor() as cursor:
			try:
				if score_one !='0' and score_two!='0':
					print 'video id is '+str(video_id)
					print 'score_one is '+str(score_one)+' fraction'
					print 'score_two is '+str(score_two)+' fraction'
					print type(list(video_id)[0])
					print type(str(score_one))
					print type(score_one)
					# cursor.execute("insert into SubjectiveEvaluationResult (ser_ds_id,score_one,ser_after_score) values (%s,%s,%s)"[str(video_id),str(score_one),str(score_two)])
					create = SubjectiveEvaluationResult.objects.create(ser_ds_id=video_id,ser_original_score=score_one,ser_after_score=score_two)
					return HttpResponse(1)
				else:
					return HttpResponse(2)
			except Exception, e:
				# raise e
				return HttpResponse(0)
		cursor.close()

	return render(request, "index.html")

def output_post(request):
	return render(request,'output.html')

#获取当前所有模型
def getAllModel(request):
	with connection.cursor() as cursor:
		cursor.execute("select msr_model_type from seahawk_test.modelselectortask group by msr_model_type")
		models = cursor.fetchall()
	cursor.close()
	return HttpResponse(json.dumps(models))

# 获取模型下的版本
def getVersionByModel(request):
	data = request.GET
	model = data.get('model')
	with connection.cursor() as cursor:
		cursor.execute("select msr_model_sr from seahawk_test.modelselectortask where msr_model_type=%s group by msr_model_sr",[str(model)])
		allv = cursor.fetchall()#fetchone
		return HttpResponse(json.dumps(allv))

# @csrf_exempt

def getChartScatter(request):
	data = request.GET
	top = data.get('top')
	version = data.get('version')
	model = data.get('model')
	print top
	print version
	print model
	with connection.cursor() as cursor:
		cursor.execute("select msr_blurLevel from seahawk_test.modelselectortask group by msr_blurLevel ")
		blur = cursor.fetchall()
		if version !='' and top=='':
			# cursor.execute("select msr_model_sr from seahawk_test.modelselectortask  where msr_model_sr=%d",[str(version)])
			msr = tuple(version)
		elif top != '' and top != None:
			cursor.execute("select msr_model_sr from seahawk_test.modelselectortask  group by msr_model_sr limit %d"%int(top))
			msr = cursor.fetchall()
		else:
			cursor.execute("select msr_model_sr from seahawk_test.modelselectortask group by msr_model_sr")
			msr = cursor.fetchall()
		cursor.execute("select msr_model_type from seahawk_test.modelselectortask group by msr_model_type")
		models = cursor.fetchall()
		# cursor.execute("select msr_blurLevel,FORMAT(msr_sr_score,2)\
		# 	from seahawk_test.modelselectortask  group by msr_blurLevel limit 10")
		# # row = cursor.fetchone()
		# row = cursor.fetchall()
		a={}
		a['msr_name']=[]
		a['modeltype']=models
		for i in range(len(msr)):
			a['msr_name'].append(list(msr[i])[0])
			a['array'+str(i)] = []
			for x in blur:
				cursor.execute("select msr_blurLevel,format(AVG(msr_sr_score),2),msr_model_sr,msr_modelDate from seahawk_test.modelselectortask \
					where msr_blurLevel=%s and msr_model_sr=%s ",[str(x[0]),str(list(msr[i])[0])])
				c = cursor.fetchall()
				a['array'+str(i)].append(c[0])
	cursor.close()
	return HttpResponse(json.dumps(a))

def getChartPolyline(methods=['GET']):
	with connection.cursor() as cursor:
		cursor.execute("select CONCAT(msr_model_sr,'_',msr_resResolution,'_',msr_sr),format(msr_sr_total_time,2) from modelselectortask limit 10")
		row = cursor.fetchall()
		cursor.execute("select v_modelDate,v_version from modelselectortaskviewscore group by v_modelDate")
		date = cursor.fetchall()
		cursor.execute("select v_model_sr from modelselectortaskviewscore group by v_model_sr limit 7")
		name = cursor.fetchall()
		# cursor.execute("select v_modelDate from modelselectortaskviewscore group by v_modelDate")
		# name = cursor.fetchall()
		cursor.execute("SELECT v_version,GROUP_CONCAT(v_sr_score ORDER BY v_sr_score DESC) AS videoScore \
				FROM modelselectortaskviewscore GROUP BY v_model_sr limit 9")
		c=cursor.fetchall()
		a = {}
		a['data'] = c
		a['datelist'] = []
		a['name'] = []
		a['array'] = []
		for i in name:
			a['name'].append(i[0])
		for i in date:
			a['datelist'].append(i[0])
		for i in list(c):
			a['array'].append(str(list(i)[1]).split(','))
	cursor.close()
	return HttpResponse(json.dumps(a))

def getChartColumnar(methods=['GET']):
	with connection.cursor() as cursor:
		cursor.execute("select format(msr_sr_pre_time,2),format(msr_sr_npu_time,2),format(msr_sr_post_time,2),CONCAT(msr_model_sr,'_',msr_resResolution,'_',msr_sr) from modelselectortask limit 10")
		row = cursor.fetchall()
		a={}
		a['name'] = []
		a['pre'] = []
		a['npu'] = []
		a['post'] = []
		for i in row:
			a['pre'].append(i[0])
			a['npu'].append(i[1])
			a['post'].append(i[2])
			a['name'].append(i[3])
	cursor.close()
	return HttpResponse(json.dumps(a))

def getChartSuper(methods=['GET']):
	with connection.cursor() as cursor:
		cursor.execute("select CONCAT(msr_model_sr,'_',msr_resResolution,'_',msr_sr),format(msr_sr_total_time,2) from modelselectortask limit 10")
		row = cursor.fetchall()
		cursor.execute("select v_modelDate from modelselectortaskview group by v_modelDate")
		d = cursor.fetchall()
		cursor.execute("select CONCAT(msr_model_sr,'_',msr_resResolution,'_',msr_sr) as msrName from modelselectortask group by msr_model_sr limit 9")
		name = cursor.fetchall()
		# cursor.execute("select msr_model_sr from modelselectortask group by msr_model_sr")
		# b = cursor.fetchall()
		a={}
		cursor.execute("SELECT v_version,GROUP_CONCAT(v_sr_totaltime ORDER BY v_sr_totaltime DESC) AS videoScore FROM modelselectortaskview GROUP BY v_model_sr limit 9")
		c=cursor.fetchall()
		a['data'] = c
		a['datelist'] = []
		a['sr_name'] = []
		a['array'] = []
		for i in d:#遍历日期
			a['datelist'].append(str(i[0]))

		for n in name:
			a['sr_name'].append(str(n[0]))
		for i in list(c):
			a['array'].append(str(list(i)[1]).split(','))
	cursor.close()

	return HttpResponse(json.dumps(a))

@csrf_exempt
def postscore(request):
	if request.method == 'POST':
		print '@'*20
		ersr_good = request.POST['ersr_good']
		ersr_bad = request.POST['ersr_bad']
		ersr_same = request.POST['ersr_same']
		now_time = datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S')
		try:
			with connection.cursor() as cursor:
				# create = EvaluationResults.objects.create(er_sr_good=ersr_good,er_sr_bad=ersr_bad,er_sr_same=ersr_same)
				cursor.execute("insert into seahawk_test.evaluationresults (er_time,er_sr_good,er_sr_bad,er_sr_same)\
					values(%s,%s,%s,%s)",[str(now_time),str(ersr_good[:-1]),str(ersr_bad[:-1]),str(ersr_same[:-1])])
			cursor.close()
			return HttpResponse(1)
		except Exception, e:
			raise e
			return HttpResponse(0)
	else:
		raise 'Error_GET'

def getvideopath(methods=['GET']):
	with connection.cursor() as cursor:
		cursor.execute("select * from  seahawk_test.select_url")
		data = cursor.fetchall()
		# print data
		top = random.sample(list(data),20)
		a={}
		a['data']=top
		# a['data']=data
		a['td_id'] = []
		a['od_url'] = []
		a['sri_url'] = []
		# for i in data:
		for i in top:
			a['td_id'].append(str(i[0]))
			a['od_url'].append(str(i[1]))
			a['sri_url'].append(str(i[2]))
		return  HttpResponse(json.dumps(a))
	cursor.close()

def getreport(request):
	with connection.cursor() as cursor:
		cursor.execute("select td_id from seahawk_test.taskdetails")
		td_id = cursor.fetchall()
		cursor.execute("SELECT GROUP_CONCAT(CONCAT(er_sr_good))  as super,GROUP_CONCAT(CONCAT(er_sr_bad))  as bad,\
			GROUP_CONCAT(CONCAT(er_sr_same))  as same  FROM  seahawk_test.evaluationresults")
		data = cursor.fetchall()
		cursor.execute("SELECT GROUP_CONCAT(CONCAT(er_sr_good)) as super FROM seahawk_test.evaluationresults")
		er_sr_good = cursor.fetchall()
		cursor.execute("SELECT GROUP_CONCAT(CONCAT(er_sr_bad)) as bad FROM seahawk_test.evaluationresults")
		er_sr_bad = cursor.fetchall()
		cursor.execute("SELECT GROUP_CONCAT(CONCAT(er_sr_same)) as same FROM seahawk_test.evaluationresults")
		er_sr_same = cursor.fetchall()
		a = {}
		a['details'] = []
		a['data'] = data[0]

		#计算出每一个视频id 对应的超分好的次数，原视频好的次数，差不多的次数,以及随机的总数。
		for i in td_id:
			esg_count = list(er_sr_good[0])[0].split(',').count(str(i[0]))
			esb_count = list(er_sr_bad[0])[0].split(',').count(str(i[0]))
			ess_count = list(er_sr_same[0])[0].split(',').count(str(i[0]))
			a['details'].append({'id':i[0],'er_sr_good':esg_count,'er_sr_bad':esb_count,'er_sr_same':ess_count,'RandomNumber':esg_count+esb_count+ess_count})
	cursor.close()

	return HttpResponse(json.dumps(a))

#饼图数据
def getPieData(request):
	data = request.GET
	with connection.cursor() as cursor:
		cursor.execute("SELECT GROUP_CONCAT(CONCAT(er_sr_good)) as super FROM seahawk_test.evaluationresults")
		er_sr_good = cursor.fetchall()
		cursor.execute("SELECT GROUP_CONCAT(CONCAT(er_sr_bad)) as bad FROM seahawk_test.evaluationresults")
		er_sr_bad = cursor.fetchall()
		cursor.execute("SELECT GROUP_CONCAT(CONCAT(er_sr_same)) as same FROM seahawk_test.evaluationresults")
		er_sr_same = cursor.fetchall()
		a = {}
		a['details'] = []
		# a['ratio'] = []
		esg = len(list(er_sr_good[0])[0].split(','))
		esb = len(list(er_sr_bad[0])[0].split(','))
		ess = len(list(er_sr_same[0])[0].split(','))
		total = esg+esb+ess
		a['details'].append({'超分视频好':esg,'原始视频好':esb,'无差异':ess})
		# a['ratio'].append({'total':total,'super':"%.2f%%" % (float(esg)/float(total) * 100),'original':"%.2f%%" % (float(esb)/float(total) * 100),'almost':"%.2f%%" % (float(ess)/float(total) * 100)})
	cursor.close()
	return HttpResponse(json.dumps(a))